<template>
  <div class="system-chart task-mt12">
    <div class="chart-header task-flex task-ai">
      <div class="task-span1 task-flex task-ai">
        <div class="chart-icon task-bjc2 task-mr12"><i class="iconfont icon-signal-fill"></i></div>
      </div>
      <div class="task-ml12 task-pointer">
        <el-dropdown @command="handleClick">
          <div>
            <i class="iconfont icon-paixu1"></i>
            {{sort}}
            <i class="iconfont icon-triangle-down"></i>
          </div>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item :command="$t('report.taskSelect.text1')">{{$t('report.taskSelect.text1')}}</el-dropdown-item>
            <el-dropdown-item :command="$t('report.taskSelect.text2')">{{$t('report.taskSelect.text2')}}</el-dropdown-item>
            <el-dropdown-item :command="$t('report.taskSelect.text3')">{{$t('report.taskSelect.text3')}}</el-dropdown-item>
            <el-dropdown-item :command="$t('report.taskSelect.text4')">{{$t('report.taskSelect.text4')}}</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
      <div class="task-flex task-pointer">
        <div class="task-ml12" @click="downLoadImage">
          <i class="iconfont icon-cloud-download"></i>
          {{ $t('product.component.qrcodeDialog.btn2') }}
        </div>
      </div>
    </div>
    <!-- 折线图 -->
    <div class="chart-content" v-if="taskCharts.length">
      <div id="chart"></div>
    </div>
    <!-- 表格 -->
    <div class="table task-mt12" v-show="tableNames.length">
      <div class="chart-header task-flex task-ai task-pointer">
        <div class="task-span1"></div>
        <div class="task-flex">
          <div @click="taskExport(false)" v-if="isButtonDisplayed && exportAuth">
            <i class="iconfont icon-upload1"></i>
            {{ $t('common.base.export') }}
          </div>
          <div class="task-ml12" @click="taskExport(true)" v-if="isButtonDisplayed && exportAuth">
            <i class="iconfont icon-upload1"></i>
            {{ $t('common.base.exportAll') }}
          </div>
          <div class="task-ml12" @click="tableNames = []">
            {{ $t('common.base.collapse') }}
            <i class="iconfont icon-triangle-down"></i>
          </div>
        </div>
      </div> 
      <!-- table -->
      <el-table
        stripe
        border
        :data="tableNames"
        ref="multipleTable"
        header-row-class-name="common-list-table-header taks-list-table-header"
      >
        <el-table-column
          v-for="(item, index) in tablename"
          :key="index"
          :label="item.displayName"
        >
          <template slot-scope="scope">
            <!-- 工单编号 -->
            <template v-if="item.fieldName === 'taskNo'">
              <a
                href=""
                class="view-detail-btn task-list-numbering"
                @click.stop.prevent="openTaskTab(scope.row.id, scope.row[item.fieldName])"
              >
                {{scope.row[item.fieldName]}}
              </a>
            </template>

            <template v-else-if="item.fieldName === 'excutorName'">
              <template v-if="isOpenData">
                <open-data type="userName" :openid="scope.row.executorStaffId"></open-data>
              </template>
              <template v-else>
                {{ scope.row.excutorName }}
              </template>
            </template>
            
            <template v-else-if="item.fieldName === 'executorUserName'">
              <template v-if="isOpenData">
                <open-data type="userName" :openid="scope.row.executorStaffId"></open-data>
              </template>
              <template v-else>
                {{ scope.row.executorUserName }}
              </template>
            </template>

            <!-- 产品 -->
            <template v-else-if="item.fieldName === 'productName'">
              {{scope.row[item.fieldName] && scope.row[item.fieldName].join(',')}}
            </template>
            <!-- 耗时时长 -->
            <template v-else-if="item.fieldName === 'userHour'">
              {{scope.row[item.fieldName]}}h
            </template>
            <template v-else>
              {{scope.row[item.fieldName]}}
            </template>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="spare-parts-foot task-flex task-ai report-spare-parts-foot">
        <span class="task-c90">{{$t('report.system.total',{num:pagination.total})}}</span>
        <el-pagination
          class="comment-list-table-footer-pagination task-span1"
          background
          :page-sizes="defaultTableData.defaultPageSizes"
          :page-size="pageSize"
          :total="pagination.total"
          :current-page="pageNum"
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
          layout="prev, pager, next, sizes, jumper"
        >
        </el-pagination>
      </div>     
    </div>
  </div>
</template>
<script>
import { t } from '@src/locales';
import { isOpenData, openAccurateTab } from '@src/util/platform';
import echarts from 'packages/Echarts';
import _ from "lodash";
import {TABLENAME} from '../../common/tableModel'
import { formatDate } from 'pub-bbx-utils';
import qs from 'qs';
import { isBasicEditionHideProduct } from '@shb-lib/version'
import { checkButtonDisplayed } from '@src/util/dom';
import { defaultTableData } from '@src/util/table'
// API
import * as ReportApi from '@src/api/ReportApi.ts';
import { safeNewDate } from '@src/util/time';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'

export default {
  name: 'task-chart',
  props: {
    taskCharts: {
      type: Array,
    }, // 图表数据
    params: {
      type: Object
    }, // table参数
    reportType: {
      type: String,
    }, // 类型
  },
  watch: {
    taskCharts(v) {
      this.histogram(v)
    },
    isBasicEditionHideProduct: {
      immediate: true,
      handler(newValue, _) {
        if (newValue) {
          this.tablename = TABLENAME.filter(item => item.fieldName !== 'productName')
        } else {
          this.tablename = TABLENAME || []
        }
      }
    }
  },
  data() {
    return {
      defaultTableData,
      isOpenData,
      isButtonDisplayed: checkButtonDisplayed(),
      tablename: TABLENAME || [],
      sort: t('report.taskSelect.text1'),
      pageSize: 10,
      pageNum: 1,
      tableNames: [], // table列表
      pagination: {}, // 分页
      timeInterval: '',
    }
  },
  computed: {
    // 基础版功能是否隐藏产品
    isBasicEditionHideProduct() {
      return isBasicEditionHideProduct() 
    },
    exportAuth() {
      let initData = JSON.parse(sessionStorage.getItem('_init_data'))
      return initData.auths?.REPORT_EXPORT || 0
    },
  },
  methods: {
    // 排序
    handleClick(v) {
      this.sort = v
      let consumeType
      switch (v) {
      case t('report.taskSelect.text2'):
        consumeType = 1
        break;
      case t('report.taskSelect.text3'):
        consumeType = 2
        break;  
      case t('report.taskSelect.text4'):
        consumeType = 3
        break;      
      default:
        consumeType = 0
        break;
      }
      this.$emit('taskTable', {
        consumeType,
      })
      // 工单开始时间筛选埋点
      this.chartTrack('REPORT_TASK_TIME_SEARCH')
    },
    // 转成图片并下载
    convertCanvasToImage() {
      const canvas = document.querySelector('#chart div canvas')
      const img = canvas.toDataURL('image/png');
      const oA = document.createElement('a');
      oA.download = '折线统计图表';// 设置下载的文件名，默认是'下载'
      oA.href = img;
      document.body.appendChild(oA);
      oA.click();
      oA.remove();
    },
    downLoadImage() {
      this.convertCanvasToImage()
      // 下载图片埋点
      this.chartTrack('DOWNLOAD_REPORT_IMAGE')
    },
    chartTrack(trackId) {
      this.reportType && this.$track.commonFn.chartTrack(this.reportType, trackId, this.$track)
    },
    // 柱状图
    histogram(data) {
      this.$nextTick(() => {
        if (!document.getElementById('chart')) return
        const myChart = echarts.init(document.getElementById('chart'))
        window.addEventListener('resize', _.debounce(function(){
          myChart.resize();
        }))
        const option = {
          tooltip: {
            trigger: 'item',
            formatter: '{b} : {c} '
          },
          xAxis: {
            type: 'category',
            data: [`<=12${t('common.base.hour1')}`, `12~24${t('common.base.hour1')}`, `24~48${t('common.base.hour1')}`, `48~72${t('common.base.hour1')}`, `72~168${t('common.base.hour1')}`, `>168${t('common.base.hour1')}`]
          },
          yAxis: {
            type: 'value'
          },
          series: [{
            data,
            type: 'bar',
            showBackground: true,
            backgroundStyle: {
              color: 'rgba(220, 220, 220, 0.8)'
            },
            barWidth : 30,
            itemStyle: {
              normal: {
                color: '#55b7b4'
              }
            },
            label: {
              show: true,
              position: 'top',
            }
          }],
          backgroundColor: '#fff'
        };

        this.tableNames = []
        if(!data.length) return
      
        myChart.setOption(option, true);

        this.pageSize = 10
        this.pageNum = 1
        myChart.on('click', e => {
          this.pageSize = 10
          this.pageNum = 1
          this.finishedTimeCountPage(e)
        })
      })
    },
    /**
     * @description 打开工单详情tab
     * @param {String} taskId 工单id
     */
    openTaskTab(taskId, taskNo) {
      if (!taskId) return;

      let fromId = window.frameElement.getAttribute('id');

      // this.$platform.openTab({
      //   id: `task_view_${taskId}`,
      //   title: `工单${taskNo}`,
      //   close: true,
      //   url: `/task/view/${taskId}?noHistory=1`,
      //   fromId,
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageTaskView,
        key: taskId,
        titleKey: taskNo,
        params: 'noHistory=1',
        fromId
      })
    },
    // 完成table
    async finishedTimeCountPage({name}) {
      const {pageSize, pageNum} = this
      let timeInterval
      switch (name) {
      case `<=12${t('common.base.hour1')}`:
        timeInterval = 0
        break;
      case `12~24${t('common.base.hour1')}`:
        timeInterval = 1
        break;  
      case `24~48${t('common.base.hour1')}`:
        timeInterval = 2
        break; 
      case `48~72${t('common.base.hour1')}`:
        timeInterval = 3
        break; 
      case `72~168${t('common.base.hour1')}`:
        timeInterval = 4
        break;     
      default:
        timeInterval = 5
        break;
      }
      
      if(typeof name === 'number') timeInterval = name
      this.timeInterval = timeInterval

      const params = {...this.params, timeInterval, pageSize, pageNum}
      let res;
      if (this.reportType === 'task_success') {
        // 完成
        res = await ReportApi.finishedTimeCountPage(params)
      } else {
        // 未完成
        res = await ReportApi.unFinishedTimeCountPage(params)
      }
      const {list, total} = res
      this.tableNames = list.map(item => {
        item.planDateTime = formatDate(safeNewDate(item.planDateTime).getTime(), 'YYYY-MM-DD HH:mm:ss') || ''
        item.completeDateTime = formatDate(safeNewDate(item.completeDateTime).getTime(), 'YYYY-MM-DD HH:mm:ss') || ''
        return item
      })
      this.pagination = {
        total,
      };
    },
    // 导出
    taskExport(isExportAll) {
      const {timeInterval} = this
      const params = {...this.params, timeInterval: isExportAll ? '' : timeInterval, isExportAll}
      if (this.reportType === 'task_success') window.location.href = `/api/report/outside/stats/task/finishedTimeCount/export?${qs.stringify(params)}`
      if (this.reportType === 'task_failure') window.location.href = `/api/report/outside/stats/task/unFinishedTimeCount/export?${qs.stringify(params)}`
      
      this.$emit('export-track', isExportAll)
    },
    /* 分页条数切换 */
    handleSizeChange(value) {
      this.pageNum = 1
      this.pageSize = value;
      this.finishedTimeCountPage({name: this.timeInterval});
    },
    /* 分页页数切换 */
    handlePageChange(value) {
      this.pageNum = value;
      this.finishedTimeCountPage({name: this.timeInterval});
    },
  }
}
</script>
<style lang="scss" scoped>
@import '../system.scss';
</style>
